<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/26
 * Time: 9:06
 */

namespace Admin\Controller;


use Common\Controller\AdminController;
use Think\Verify;

class LoginController extends AdminController
{
	public function index(){
		if (IS_POST){
			if ($this->isLogin($_POST)){
				$user = M('admin')->find();
//				$this->p($user);

				// //更新登录时间与IP
				 $update = array(
				 	'aid' => $user['aid'],
				 	'logintime' => $_SERVER['REQUEST_TIME'],
				 	'loginip' => get_client_ip(),
				 	);
				 M('admin')->save($update);

				// //保存登录信息于session中
				 $_SESSION['aid'] = $user['aid'];
				 $_SESSION['aname'] = $user['adminname'];
				 $_SESSION['logintime'] = date('Y-m-d H:i:s', $user['logintime']);
				 $_SESSION['loginip'] = $user['loginip'];
				 $_SESSION['curtime'] = date('Y-m-d H:i:s', $update['logintime']);
				 $_SESSION['curip'] = $update['loginip'];
				// //用于判断登入后台后是否出现欢迎框，刚登录就出现，刷新不出现
				 $_SESSION['welcome'] = 1;
//$this->p($_SESSION);
				// 登录成功，跳转到后台首页
				redirect(__ROOT__.'/index.php/Admin');
			}
		}
		$this->display();
	}
	/**
	 * 显示验证吗
	 */
	public function verify(){
		$config =    array(
			'fontSize'    =>    100,    // 验证码字体大小
			'length'      =>    3,     // 验证码位数
			'useNoise'    =>    false, // 关闭验证码杂点
			'expire'      =>    10,   //验证码的有效期（秒）
		);
		$Verify = new Verify($config);
		$Verify->entry();
	}
	/**
	 * 验证吗验证
	 * 检测输入的验证码是否正确
	 * $code为用户输入的验证码字符串
	 */
	public function check_verify($code, $id = ''){
		$verify = new Verify();
		return $verify->check($code, $id);
	}
	/**
	 * 退出登录
	 * @return [type] [description]
	 */
	public function logout(){
		session_unset();
		session_destroy();
		$this->success('退出成功，请登录','index');
	}
	public function isLogin($data){
//		$this->p($_POST);
//		$this->p($_SESSION);
//		$this->p($data);
		//检验是否正常提交的数据
		if (!isset($_POST['sub'])){
			$this->error('请正常提交',U('index'),2);exit;
		}
		//检验用户名和密码
		$user = M('admin')->find();
//		$this->p($user);

		if (!$user['adminaccount']==$_POST['username']){
			$this->error('用户名不正确',U('index'),2);
			exit;
		}

		if (!$user['adminpwd']==$_POST['password']){

			$this->error('密码不正确',U('index'),2);
			exit;
		}
		//检验验证码
		if (!$this->check_verify($data['verify'])){
			$this->error('验证码不正确',U('index'),2);
			exit;
		}
		return true;
	}
}